package com.example.springboot.service.impl;

import com.example.springboot.controller.request.BaseRequest;
import com.example.springboot.entity.Notice;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.NoticeMapper;
import com.example.springboot.service.INoticeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class NoticeService implements INoticeService {

    @Autowired //通过autowired导入noticeMapper
    NoticeMapper noticeMapper;

    public List<Notice> list(){
        return noticeMapper.list();
    }

    @Override
    public PageInfo<Notice> page(BaseRequest baseRequest){
//        dependency引入pagehelper
//        PageHelper传入页面和每页信息条数
        PageHelper.startPage(baseRequest.getPageNum(),baseRequest.getPageSize());
        List<Notice> notices=noticeMapper.listByCondition(baseRequest);
        return new PageInfo<>(notices);
    }

    @Override
    public void save(Notice notice){//        当做卡号来处理
        Date date= new Date();
//     通过hashCode编码将fastSimpleUUID产生的字母和数字转为数字
        try{
            noticeMapper.save(notice);
        }catch(DuplicateKeyException e){
            log.error("数据插入失败,title:{}",notice.getTitle());
            throw new ServiceException("用户插入失败");
        }
    }


    @Override
    public Notice getById(Integer id) {
        return noticeMapper.getById(id);
    }

    @Override
    public void update(Notice notice) {
        notice.setUpdateTime(new Date());
        noticeMapper.updateById(notice);

    }

    @Override
    public void deleteById(Integer id) {
        noticeMapper.deleteById(id);
    }
    
}
